import random
import sys
import time
import redis

import controller
import utils
# from head import kafka_utils, collect_k8s_once


def collect_head():
    if controller.check_stop_signal():
        ips = controller.get_down_ip("head")
        for ip in ips:
            controller.set_stop_signal(ip.rstrip("\n"))
        sys.exit(0)
    # try:
    rdb = redis.Redis(host="localhost", port=6379, db=1, decode_responses=True)
    if rdb.llen("run_head") != 0:
        topic = ""
        while rdb.llen("run_head") != 1:
            topic = rdb.rpop("run_head")
        print(topic)
        rdb.close()

        ips = controller.get_down_ip("head")
        start = time.time()
        if ips:
            for ip in ips:
                utils.send_to_redis_one(ip.rstrip("\n"), topic, "run")

        # msgs = []
        # msgs = msgs# + collect_k8s_once.collect_k8s()
        time.sleep(3)
        res = ""
        if ips:
            for ip in ips:
                msgs = utils.get_from_redis(ip.rstrip("\n"), topic)
                if msgs:
                    for msg in msgs:
                        res = res + msg + " "

        end = time.time() - start
        time.sleep(random.random() * 2)

        # ip = controller.get_up_ip("head")
        # utils.send_to_redis_ones(ip, msgs, topic)
        # kafka_utils.send_to_kafka(msgs)
        if res:
            msgs = res.split(" ")
            for msg in msgs:
                if msg:
                    print(msg)
        print(end - 3)
    else:
        rdb.close()

    # except Exception as e:
    #     print(str(e))


def heart_beat():
    if controller.check_stop_signal():
        sys.exit(0)

    ip = controller.get_up_ip("head")
    if ip:
        utils.set_redis_2(ip, 1, utils.get_network_ip(), 35)
    add_ips, red_ips = controller.check_down_ip("head", utils.check_redis_2("localhost"))
    if add_ips:
        for ip in add_ips:
            print(f"discover {ip}")
            controller.add_slave([ip])
            utils.add_line("/collector_slave/config/log/log.txt", f"discover slave: {ip}")
        utils.add_line("/collector_slave/config/log/log.txt", f"{time.time()}")
        utils.add_line("/collector_slave/config/log/log.txt", "")
    if red_ips:
        print("please check these nodes:")
        for ip in red_ips:
            print(ip)
            controller.delete_slave([ip])
            utils.add_line("/collector_slave/config/log/log.txt", f"please check slave: {ip}")
        utils.add_line("/collector_slave/config/log/log.txt", f"{time.time()}")
        utils.add_line("/collector_slave/config/log/log.txt", "")


def run_head():
    t = utils.RepeatingTimer(1.0, collect_head)
    h = utils.RepeatingTimer(10.0, heart_beat)
    t.start()
    h.start()
